package com.zxw.springtest.login.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.zxw.springtest.login.service.LoginService;
import com.zxw.springtest.utils.BaseController;

/**
 * 类描述		总入口
 * @author zhengxw
 * @since 
 */
@Controller
@RequestMapping("/login/")
public class LoginController extends BaseController{
	@Autowired
	private LoginService loginService;
	
	/**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="toLogin")
	public ModelAndView toLogin()throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("redirect:/login.jsp");
		return mv;
	}
	
	/**
	 * 首页
	 * @return
	 */
	@RequestMapping(value="success")
	public ModelAndView index()throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("redirect:/success.jsp");
		return mv;
	}

	@RequestMapping(value="login", produces="application/json;charset=UTF-8") 
	@ResponseBody
    private ModelAndView hello(
            @RequestParam(value = "username", required = false)String username,  
            @RequestParam(value = "password", required = false)String password,
            @RequestParam(value = "verifyCode", required = false)String codeValue,
            HttpServletRequest req ,HttpServletResponse resp
            ) throws Exception{
		ModelAndView mv = this.getModelAndView();
		String errorMsg = null;
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
        boolean checkRs = SimpleImageCaptchaServlet.validateResponse(req, codeValue);
        if(checkRs){        	
//        	Boolean isLogin = loginService.login(username,password);
//        	if(isLogin){
        		//shiro加入身份验证（在自定义realm中判断用户名，密码）
				Subject subject = SecurityUtils.getSubject(); 
			    UsernamePasswordToken token = new UsernamePasswordToken(username, password); 
			    try{
					subject.login(token);
				}catch (UnknownAccountException e) {
					errorMsg = "账号不存在！";
				}catch (IncorrectCredentialsException e) {
					errorMsg = "用户名或者密码不正确！";
				}catch (Exception e) {
					errorMsg = "其他错误"+e.getMessage();
				}
//        	}else{
//        		errorMsg = "usererror"; 				//用户名密码校验失败
//        	}
        }else{
        	errorMsg="codeError";
        }
        if(StringUtils.isEmpty(errorMsg)){
        	errorMsg = "success";				//验证成功        	
		}
        //登陆信息写会session
        session.setAttribute("loginMsg", errorMsg);
        if("success".equals(errorMsg)){
        	mv.setViewName("redirect:/success.jsp");
        }else{
        	mv.setViewName("redirect:/login.jsp");
        }       
		
		return mv;
    }
}
